package com.sj.uabrowser.mvp.video.view.fragment;


import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.PopupWindow;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.classic.common.MultipleStatusView;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.GSYVideoHelper;
import com.shuyu.gsyvideoplayer.video.NormalGSYVideoPlayer;
import com.sj.uabrowser.MainActivity;
import com.sj.uabrowser.R;
import com.sj.uabrowser.app.Constant;
import com.sj.uabrowser.app.SHASecrete;
import com.sj.uabrowser.framework.LazyLoadFragment;
import com.sj.uabrowser.mvp.video.bean.NVideoItem;
import com.sj.uabrowser.mvp.video.bean.NVideoTab;
import com.sj.uabrowser.mvp.video.bean.VideoItem;
import com.sj.uabrowser.mvp.video.contract.VideosContract;
import com.sj.uabrowser.mvp.video.presenter.VideosPresenter;
import com.sj.uabrowser.mvp.video.videoutils.RecyclerItemViewHolder;
import com.sj.uabrowser.mvp.video.view.adp.RecyclerBaseAdapter;
import com.vondear.rxtool.RxNetTool;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;


/**
 * A simple {@link Fragment} subclass.
 */
public class VideoFragment extends LazyLoadFragment<VideosContract.Presenter> implements VideosContract.View/*, ContentAD.ContentADListener, NativeExpressAD.NativeExpressADListener*/ {

    @BindView(R.id.rv_videos)
    RecyclerView rvVideos;
    @BindView(R.id.multipleStatusView)
    MultipleStatusView multipleStatusView;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.fragmentContainer)
    View fragmentContainer;

    private String keys;
    ArrayList<MultiItemEntity> datas;
    private RecyclerBaseAdapter recyclerBaseAdapter;
    private GSYVideoHelper smallVideoHelper;
    private GSYVideoHelper.GSYVideoHelperBuilder gsySmallVideoHelperBuilder;
    int lastVisibleItem;

    int firstVisibleItem;
    private PopupWindow popupWindow;
    private int switch_status;
    private static final int num = 10;

    public static final int AD_COUNT = 1;    // 加载广告的条数，取值范围为[1, 10]
    public static int FIRST_AD_POSITION = 2; // 第一条广告的位置
    public static int ITEMS_PER_AD = 0;     // 每间隔10个条目插入一条广告

    public static final int DOWN_PULL = 1;
    public static final int UP_PULL = 2;
    private int direct = UP_PULL;

    @Override
    public VideosContract.Presenter createPresenter() {
        return new VideosPresenter(this);
    }

    @Override
    protected int setContentView() {
        return R.layout.fragment_video;
    }

    @Override
    protected void lazyLoad() {
        if (datas == null || datas.size() == 0) {
            multipleStatusView.showLoading();
            fetchVideos(keys, page);
        }
    }

    @Override
    public void setView() {
        datas = new ArrayList<>();
        keys = getArguments().getString("keys");
        multipleStatusView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RxNetTool.isNetworkAvailable(act)) {
                    datas.clear();
                    lazyLoad();
                }
            }
        });
        recyclerBaseAdapter = new RecyclerBaseAdapter(act, datas);
        setVideoItemClickListener(recyclerBaseAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(act);
        rvVideos.setLayoutManager(linearLayoutManager);
        rvVideos.setAdapter(recyclerBaseAdapter);
        rvVideos.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int firstVisibleItem, lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                //大于0说明有播放
                if (smallVideoHelper.getPlayPosition() >= 0) {
                    //当前播放的位置
                    int position = smallVideoHelper.getPlayPosition();
                    //对应的播放列表TAG
                    if (smallVideoHelper.getPlayTAG().equals(RecyclerItemViewHolder.TAG)
                            && (position < firstVisibleItem || position > lastVisibleItem)) {
                        //如果滑出去了上面和下面就是否，和今日头条一样
                        if (!GSYVideoManager.isFullState(getActivity())) {
                            GSYVideoManager.releaseAllVideos();
//                            recyclerBaseAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });

//内容跟随偏移
        mRefreshLayout.setEnableHeaderTranslationContent(true);
        mRefreshLayout.setEnableFooterTranslationContent(true);
        //设置下拉刷新主题颜色
        mRefreshLayout.setPrimaryColorsId(R.color.color_lighter_gray, R.color.color_title_bg);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {//下拉
                if (datas != null) {
                    datas.clear();
//                    mAdViewPositionMap.clear();
//                    recyclerBaseAdapter.notifyDataSetChanged();
                }
                direct = DOWN_PULL;
                if (RxNetTool.isAvailable(act)) {
//                    multipleStatusView.showContent();
//                    datas.clear();
//                    recyclerBaseAdapter.notifyDataSetChanged();
//                fetchVideos(keys,page=1);
                    page = 0;
                    refreshVideos(keys);
                } else {
                    mRefreshLayout.finishRefresh();
                    multipleStatusView.showNoNetwork();
                }
            }
        });
        //设置 Footer 为 球脉冲 样式
        mRefreshLayout.setRefreshFooter(new BallPulseFooter(act).setSpinnerStyle(SpinnerStyle.Scale));
        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                direct = UP_PULL;
                if (flag) fetchVideos(keys, page);
                else {
                    mRefreshLayout.finishLoadmore();
                    mRefreshLayout.setEnableLoadmore(false);
                }
            }
        });
        recyclerBaseAdapter.setAdpShareItemClick(new RecyclerBaseAdapter.AdpShareItemClick() {
            @Override
            public void OnSharedClick(int position) {
//                onShare((VideoItem) datas.get(position));
            }
        });
        recyclerBaseAdapter.setAdpReplayItemClick(new RecyclerBaseAdapter.AdpReplayItemClick() {
            @Override
            public void onReplayCick(int position) {
                MultiItemEntity bean = datas.get(position);
                if (bean instanceof NVideoItem) {
                    NVideoItem videoItem = (NVideoItem) bean;
                    TreeMap<String, Object> params = new TreeMap<>();
                    params.put("id", videoItem.getId());
//                    params.put("sources", videoItem.getSources());
//                    params.put("videoUrl", videoItem.getVideoUrl());
//                    check(params);
                    if (presenter != null)
                        presenter.updateVideoUrl(params, position);
                }
            }
        });


        smallVideoHelper = new GSYVideoHelper(act, new NormalGSYVideoPlayer(act));
        FrameLayout videoFullContainer = ((MainActivity) getActivity()).videoFullContainer;
        if (videoFullContainer != null) {
            smallVideoHelper.setFullViewContainer(videoFullContainer);
        }

        //配置
        gsySmallVideoHelperBuilder = new GSYVideoHelper.GSYVideoHelperBuilder();
        gsySmallVideoHelperBuilder
                .setHideActionBar(true)
                .setHideStatusBar(true)
                .setNeedLockFull(true)
                .setCacheWithPlay(false)
                .setAutoFullWithSize(true)
                .setShowFullAnimation(true)
                .setLockLand(true).setVideoAllCallBack(new GSYSampleCallBack() {

            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
                Debuger.printfLog("Duration " + smallVideoHelper.getGsyVideoPlayer().getDuration() + " CurrentPosition " + smallVideoHelper.getGsyVideoPlayer().getCurrentPositionWhenPlaying());
            }

            @Override
            public void onEnterFullscreen(String url, Object... objects) {
                super.onEnterFullscreen(url, objects);
                ((MainActivity) getActivity()).showVideoFull();
            }

            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                super.onQuitFullscreen(url, objects);
                ((MainActivity) getActivity()).hideVideoFull();
            }


            @Override
            public void onQuitSmallWidget(String url, Object... objects) {
                super.onQuitSmallWidget(url, objects);
                //大于0说明有播放,//对应的播放列表TAG
                if (smallVideoHelper.getPlayPosition() >= 0 && smallVideoHelper.getPlayTAG().equals(RecyclerItemViewHolder.TAG)) {
                    //当前播放的位置
                    int position = smallVideoHelper.getPlayPosition();
                    //不可视的是时候
                    if ((position < firstVisibleItem || position > lastVisibleItem)) {
                        //释放掉视频
                        smallVideoHelper.releaseVideoPlayer();
                        recyclerBaseAdapter.notifyDataSetChanged();
                    }
                }

            }
        });

        smallVideoHelper.setGsyVideoOptionBuilder(gsySmallVideoHelperBuilder);

        recyclerBaseAdapter.setVideoHelper(smallVideoHelper, gsySmallVideoHelperBuilder);

//        int switch_status = Util_SharedPrefenences.get(act,Util_SharedPrefenences.KEY_CONTENTAD2,BannerConnsts.SWITCH_OFF);
//        if(switch_status == BannerConnsts.SWITCH_ON)
//              loadAD();
    }

//    private ContentAD contentAD;
    //初始化并加载广告
//    public void loadAD() {
//        Logger.e("loadAD");
//        if (contentAD == null) {
//            this.contentAD = new ContentAD(act, BannerConnsts.APPID, BannerConnsts.ContentADPosID2, this);
//        }
//        int pageNumber = 1;
//        int channel = 105;
//        boolean isManualOperation = true;
//        contentAD.loadAD(pageNumber, channel, isManualOperation);
//    }


    private void copyAddr(VideoItem videoItem) {
        ClipData myClip = ClipData.newPlainText("text", videoItem.getVideoUrl());
        ClipboardManager myClipboard = (ClipboardManager) act.getSystemService(Activity.CLIPBOARD_SERVICE);
        myClipboard.setPrimaryClip(myClip);
        showToast("已复制到剪切板");
        if (popupWindow != null)
            popupWindow.dismiss();
    }

    int page = 1;

    @Override
    public void setData() {

    }

    private void fetchVideos(String cId, int page) {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("category", cId);
        params.put("page", page - 1);
//        params.put("number", num);
        check(params);
        if (presenter != null)
            presenter.fetchVideos(params);
    }

    private void refreshVideos(String cId) {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("category", cId);
//        params.put("number", num);
        check(params);
        if (presenter != null)
            presenter.refreshVideos(params);
    }

    boolean flag = true;

    @Override
    public void showTabVideoList(List<NVideoTab> videoTab) {

    }

    @Override
    public void showVideosList(List<NVideoItem> videoNav) {
        multipleStatusView.showContent();
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadmore();
//        page = videoNav.getPage();
        Logger.e("page:" + page);
//        if (videoNav.getCurrentSize() >= videoNav.getPageSize()) {
//            page++;
//            flag = true;
//        } else {
//            flag = false;
//            Util.showToastShort("没有更多视频了！");
//        }
//        ArrayList<VideoItem> datas0 = videoNav.getList();
        page++;
        if (direct == DOWN_PULL) {
            datas.addAll(0, videoNav);
        } else if (direct == UP_PULL) {
            datas.addAll(videoNav);
        }
        recyclerBaseAdapter.notifyDataSetChanged();
        if (datas.size() == 0) {
            multipleStatusView.showEmpty();
        }
    }


    @Override
    public void updateVideoUrl(String url, int position) {
        Logger.e("更新url成功：" + url);
        smallVideoHelper.releaseVideoPlayer();
        ((NVideoItem) datas.get(position)).setVideo_url(url);
        recyclerBaseAdapter.notifyItemChanged(position);
        if (videoItemClickListener != null) {
            videoItemClickListener.onVideoItemClick(url, position);
        }
    }


    public VideoItemClickListener videoItemClickListener;

    public void setVideoItemClickListener(VideoItemClickListener videoItemClickListener) {
        this.videoItemClickListener = videoItemClickListener;
    }


    public interface VideoItemClickListener {
        void onVideoItemClick(String url, int position);

        void onVideoItemPause();
    }


    @Override
    public void showError(String msg, int errorCode) {
        if (mRefreshLayout != null) {
            mRefreshLayout.finishRefresh();
        }
        if (multipleStatusView != null && datas.size() == 0) {
            multipleStatusView.showEmpty();
        }
    }


    public boolean onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(getActivity())) {
            return true;
        }
        return false;
    }

    public void onVideoPause() {
        if (videoItemClickListener != null) {
            Logger.e("fragment onPause. ");
            videoItemClickListener.onVideoItemPause();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        onVideoPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Logger.e("Video Fragment:" + hidden);
    }

    @Override
    public void onResume() {
        super.onResume();
//        GSYVideoManager.onResume();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        smallVideoHelper.releaseVideoPlayer();
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            VideoListFragment videoListFragment = (VideoListFragment) getParentFragment();
            if (videoListFragment != null) {
                videoListFragment.notifyAdpUpdate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String check(TreeMap<String, Object> params) {
        params.put("appId", Constant.AppId);
        params.put("time", new Date().getTime());
        StringBuilder sign = new StringBuilder();
        for (String s : params.keySet()) {
            sign.append(s + params.get(s));
        }
        sign.append(Constant.AppSecret);
        String sign0 = SHASecrete.getDigestOfString(sign.toString().getBytes()).toUpperCase();
        params.put("sign", sign0);
        return sign0;
    }


}
